package com.example.localareanetworkchat.fragment.profile

import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.widget.Toolbar
import androidx.lifecycle.ViewModelProvider
import com.example.localareanetworkchat.R
import com.example.localareanetworkchat.fragment.MainViewModel
import com.example.localareanetworkchat.login.LoginActivity
import kotlinx.android.synthetic.main.fragment_profile.*

class ProfileFragment : Fragment() {

    private var viewModel: MainViewModel ?= null

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_profile, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        requireActivity().findViewById<Toolbar>(R.id.toolbar).title = "个人"

        viewModel = ViewModelProvider(requireActivity(), ViewModelProvider.AndroidViewModelFactory(requireActivity().application)).get(MainViewModel::class.java)
        tv_chat_user_profile_name_first.text = viewModel?.user?.name?.first()?.uppercase()
        tv_chat_user_profile_name.text = viewModel?.user?.name
        tv_chat_user_profile_uid.text = viewModel?.user?.uid

        tv_chat_user_profile_logout.setOnClickListener {
            val dialogBuilder = AlertDialog.Builder(requireContext())
            dialogBuilder.setTitle("提示")
            dialogBuilder.setMessage("是否退出登录？")

            dialogBuilder.setPositiveButton("确定") { _, _ ->
                viewModel?.stopHttpServer()
                startActivity(Intent(context, LoginActivity::class.java))
            }
            dialogBuilder.setNegativeButton("取消") { _, _ ->
            }
            dialogBuilder.setCancelable(true)
            dialogBuilder.show()
        }
    }
}